package Interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.vma.tools.MDA;
import com.vma.tools.Encrypt;
import com.vma.tools.MD5Helper;


/**
 * Created by chenzui on 2017/5/5.
 */
public class SignInterceptor implements Interceptor {
    private Cache cache = Redis.use("tokenServer");
    public void intercept(Invocation invocation) {
        Long timeStamp =  invocation.getController().getParaToLong("timeStamp");
        String sign =  invocation.getController().getPara("sign");
        String token =  invocation.getController().getPara("token");

        System.out.println("timeStamp:"+timeStamp+"==========sign:"+sign+"=============token:"+token);

        if(validate(timeStamp,sign)){
            System.out.println("validate success");
            if(token == null || "".equals(token)){
                invocation.invoke();
            }else {
                Integer userId =  cache.get(token);
                System.out.println("===========userId:"+userId);
                if(userId != null && userId != 0){
                    invocation.getController().getRequest().setAttribute("userId",userId);
                    invocation.invoke();
                }else {

                }
            }
        }else {

        }

    }

    private boolean validate(Long timeStamp,String sign){
        byte[] keybyte= MDA.Des3Key.getBytes();
//        Long now = System.currentTimeMillis();
//        if((now - timeStamp)>1000*8){
//            return false;
//        }else {
//            String de = Encrypt.DataDecrypt(keybyte,sign);
//            String md5stamp = MD5Helper.getMD5Str(timeStamp.toString());
//            if(de.equals(md5stamp)){
//                return true;
//            }else {
//                return false;
//            }
//        }
        String de = Encrypt.DataDecrypt(keybyte,sign);
        String md5stamp = MD5Helper.getMD5Str(timeStamp.toString());
        if(de.equals(md5stamp)){
            return true;
        }else {
            return false;
        }
    }
    public static void main(String[] args){
        System.out.println(Encrypt.DataEncrypt(MDA.Des3Key.getBytes(),MD5Helper.getMD5Str("1495272203")));
    }
}
